package com.luom.springbootinit.utils;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import com.luom.springbootinit.config.MailConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;

@Slf4j
@Component
@AllArgsConstructor
public class SendEmail {

    private final JavaMailSenderImpl javaMailSender;

    private final MailConfig mailConfig;

    /**
     * 发送带附近的邮件信息
     * @param to 收件人
     * @param code  验证码
     */
    public boolean sendMail(String to,  String code) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject("验证码");
//            helper.setText(content, true);
            helper.setText(buildCodeContent(code), true);
            helper.setTo(to);
            helper.setFrom(mailConfig.getNickname()+ '<' + mailConfig.getUsername() + '>');
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }



    /**
     * 读取邮件模板
     * 替换模板中的信息
     * @param code 内容
     * @return
     */
    public String buildCodeContent(String code) {
        //加载邮件html模板
        Resource resource = new ClassPathResource("mailtemplate.html");
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.info("发送邮件读取模板失败: {}", e.getMessage());
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error("",e);
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(), "17633434352", "2871389499@qq.com", code);
    }
}
